/*
 * AuthorsPanel.java
 *
 * Created on 16 de julio de 2007, 18:29
 */

package Interfaz;

import Modelo.Author;
import Modelo.Util;
import java.util.Vector;
import javax.swing.DefaultListModel;

/**
 *
 * @author  Ignacio
 */
public class AuthorsPanel extends javax.swing.JPanel {
    
    /** Creates new form AuthorsPanel */
    
    public AuthorsPanel() {
        initComponents();
        DefaultListModel model = new DefaultListModel();
        this.listAuthors.setModel( model );
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        lFirstName = new javax.swing.JLabel();
        lLastName = new javax.swing.JLabel();
        lEmail = new javax.swing.JLabel();
        tFirstName = new javax.swing.JTextField();
        tLastName = new javax.swing.JTextField();
        tEmail = new javax.swing.JTextField();
        bAdd = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        listAuthors = new javax.swing.JList();
        bUp = new javax.swing.JButton();
        bRemove = new javax.swing.JButton();
        bDown = new javax.swing.JButton();

        lFirstName.setText("First Name");

        lLastName.setText("Last Name");

        lEmail.setText("Email");

        tFirstName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tFirstNameActionPerformed(evt);
            }
        });

        tLastName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tLastNameActionPerformed(evt);
            }
        });

        tEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tEmailActionPerformed(evt);
            }
        });

        bAdd.setText("Add");
        bAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAddActionPerformed(evt);
            }
        });

        listAuthors.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(listAuthors);

        bUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/go-up.png")));
        bUp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bUpActionPerformed(evt);
            }
        });

        bRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/list-remove.png")));
        bRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bRemoveActionPerformed(evt);
            }
        });

        bDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/go-down.png")));
        bDown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bDownActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lLastName, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)
                                .addGap(17, 17, 17))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lEmail)
                                .addGap(43, 43, 43))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lFirstName)
                                .addGap(16, 16, 16)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(tFirstName, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
                            .addComponent(tLastName)
                            .addComponent(tEmail)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(bDown, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(bRemove, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(bUp, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addComponent(bAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lFirstName)
                    .addComponent(tFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lLastName)
                    .addComponent(tLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lEmail)
                    .addComponent(tEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bAdd)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bUp)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bRemove)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                        .addComponent(bDown))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void bDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bDownActionPerformed
        int index = this.listAuthors.getSelectedIndex();
        
        if( index == -1 )
            return;
        
        if( index + 1 < ((DefaultListModel)this.listAuthors.getModel()).size() )
        {
            String author = (String)((DefaultListModel)this.listAuthors.getModel()).get( index );
            ((DefaultListModel)this.listAuthors.getModel()).remove( index );
            ((DefaultListModel)this.listAuthors.getModel()).insertElementAt( author, index + 1 );
            this.listAuthors.setSelectedIndex( index + 1 );
        }
    }//GEN-LAST:event_bDownActionPerformed

    private void bRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRemoveActionPerformed
        int index = this.listAuthors.getSelectedIndex();
        
        if( index == -1 )
            return;
        
        ((DefaultListModel)this.listAuthors.getModel()).remove( index );
        
        if( ((DefaultListModel)this.listAuthors.getModel()).size() > 0 )
        {
            if( index < ((DefaultListModel)this.listAuthors.getModel()).size() )
                this.listAuthors.setSelectedIndex( index );
            else
                this.listAuthors.setSelectedIndex( index - 1 );
        }
    }//GEN-LAST:event_bRemoveActionPerformed

    private void bUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bUpActionPerformed
        int index = this.listAuthors.getSelectedIndex();
        
        if( index == -1 )
            return;
        
        if( index > 0 )
        {
            String author = (String)((DefaultListModel)this.listAuthors.getModel()).get( index );
            ((DefaultListModel)this.listAuthors.getModel()).remove( index );
            ((DefaultListModel)this.listAuthors.getModel()).insertElementAt( author, index - 1  );
            this.listAuthors.setSelectedIndex( index - 1 );
        }
    }//GEN-LAST:event_bUpActionPerformed

    private void bAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAddActionPerformed
        if(tFirstName.getText().compareTo("") == 0){
            Util.errorDialog("Error", "First name missing.");
            return;
        }
        if(tLastName.getText().compareTo("") == 0){
            Util.errorDialog("Error", "Last name missing.");
            return;
        }
        process();
    }//GEN-LAST:event_bAddActionPerformed

    public Author getAuthor( int index )
    {
        if( index < 0 || index >= ((DefaultListModel)this.listAuthors.getModel()).size() )
            return null;
        
        String author = (String)((DefaultListModel)this.listAuthors.getModel()).get( index );
        
        String name = author.split( ", " )[ 0 ];
        String lastName = author.split( ", " )[ 1 ].split( " \\(" )[ 0 ];
        String mail = "";
        if( !(author.endsWith("()")) ){
            mail = author.split( "\\(" )[ 1 ].split( "\\)" )[ 0 ];
        }
        
        return new Author(name, lastName, mail);
    }
    
    public Vector<Author> getAuthors()
    {
        Vector<Author> authors = new Vector<Author>();
        int size = ((DefaultListModel)this.listAuthors.getModel()).size();
        for( int i = 0 ; i < size ; i++ )
        {
            authors.add( getAuthor( i ) );
        }
        
        return authors;
    }
    
    private boolean validar()
    {
        if( this.tFirstName.getText() == "" )
        {
            Util.errorDialog( "Error", "First name is empty" );
            return false;
        }
        else if( this.tLastName.getText() == "" )
        {
            Util.errorDialog( "Error", "Last name is empty" );
            return false;
        }
        else if( this.tEmail.getText() == "" )
        {
            Util.errorDialog( "Error", "Email is empty" );
            return false;
        }
        
        return true;
    }
    
    private void process()
    {
        if( validar() )
        {
            Author author = new Author( tFirstName.getText(), tLastName.getText(), tEmail.getText() );
            addAuthor( author );
        }
    }
    
    public void addAuthor( Author author )
    {
        // si cambias este formato cambia el parseo en getAuthor
        String line = author.getSurname() + ", " + author.getName() + " (" + author.getEmail() + ")";
        
        if( ((DefaultListModel)this.listAuthors.getModel()).contains( line ) )
            return;
        
        ((DefaultListModel)this.listAuthors.getModel()).addElement( line );
        
        this.tFirstName.setText( "" );
        this.tLastName.setText( "" );
        this.tEmail.setText( "" );
        this.tFirstName.grabFocus();
    }

    // add authors
    public void addAuthors( Vector<Author> authors )
    {
        for( Author author:authors )
        {
            addAuthor( author );
        }
    }
    
    // clear and set the authors
    public void setAuthors( Vector<Author> authors )
    {
        ((DefaultListModel)this.listAuthors.getModel()).clear();
        for( Author author:authors )
        {
            addAuthor( author );
        }
    }
    
    private void tEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tEmailActionPerformed
        this.process();
    }//GEN-LAST:event_tEmailActionPerformed

    private void tLastNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tLastNameActionPerformed
        this.tEmail.grabFocus();
    }//GEN-LAST:event_tLastNameActionPerformed

    private void tFirstNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tFirstNameActionPerformed
        this.tLastName.grabFocus();
    }//GEN-LAST:event_tFirstNameActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAdd;
    private javax.swing.JButton bDown;
    private javax.swing.JButton bRemove;
    private javax.swing.JButton bUp;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lEmail;
    private javax.swing.JLabel lFirstName;
    private javax.swing.JLabel lLastName;
    private javax.swing.JList listAuthors;
    private javax.swing.JTextField tEmail;
    private javax.swing.JTextField tFirstName;
    private javax.swing.JTextField tLastName;
    // End of variables declaration//GEN-END:variables
    
}
